<?php

/**
 * @Author:      lyt
 * @DateTime:  2017-07-27 15:28:20
 * @Description: 门店套餐卡列表
 */
class ScSServiceCardController extends BaseController
{
   /**
    * @Author:      lyt
    * @DateTime:  2017-07-27 15:51:15
    * @Description: 门店套餐卡销售订单
    */
    public function service_card_order_list(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $token = Input::get('token');
            $page_size = Input::get("page_size", 10);
            $page = Input::get("page", 1);
            $create_begin_time=Input::get("create_begin_time");
            $create_end_time=Input::get("create_end_time");
            $begin_time=Input::get("begin_time");
            $end_time=Input::get("end_time");
            $order_id=Input::get("order_id");
            $user_id=Input::get("user_id");
            $order_source=Input::get("order_source");

            $sco=ServiceCardOrder::leftJoin("service_card_detail","service_card_detail.id","=","service_card_order.service_card_detail_id")->leftJoin("service_card_base","service_card_base.id","=","service_card_order.service_card_id")
            ->leftJoin("users","users.id","=","service_card_order.user_id");
            $sco=$sco->where("service_card_order.shop_id",$sc_user->shop_id);
            if($order_source){
                $sco=$sco->where("service_card_order.order_source",$order_source);
            }
            if($create_begin_time){
                $sco=$sco->where("service_card_order.created_at",">=",$create_begin_time." 00:00:00");
            }
            if($create_end_time){
                $sco=$sco->where("service_card_order.created_at","<",$create_end_time." 23:59:59");
            }
            if($begin_time){
                $sco=$sco->where("service_card_order.pay_time",">=",$begin_time." 00:00:00");
            }
            if($end_time){
                $sco=$sco->where("service_card_order.pay_time","<",$end_time." 23:59:59");
            }
            if($order_id){
                $sco=$sco->where("service_card_order.order_id","like",'%'.$order_id.'%');
            }
            if($user_id){
                $user_id_arr=Users::where("phone","like",'%'.$user_id.'%')->orWhere("real_name","like",'%'.$user_id.'%')->select("id")->get()->toArray();
                $sco=$sco->whereIn("service_card_order.user_id",$user_id_arr);
            }
            $count=$sco->count();
            $sco=$sco->orderBy("created_at","desc")->skip($page_size*($page-1))->take($page_size)->select("service_card_order.*","service_card_detail.id as card_no","service_card_base.name as card_name","users.phone","users.real_name","users.type")->get();
            $response = array('code' => 0, 'msg' => 'ok', 'result' =>array("count"=>$count,"orders"=>$sco));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "service_card_order_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

   /**
    * @Author:      lyt
    * @DateTime:  2017-07-28 09:37:36
    * @Description: 套餐卡订单详情
    * @link http://api.anhui.com/v1/scs/service_card/service_card_order_detail?token=53b2544d6c29e928d626657673b88080&order_id=15272359136938
    */
    public function service_card_order_detail(){
        $validator = Validator::make(Input::all(),
            array(
                'token'        => 'required',
                'order_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $sco=ServiceCardOrder::leftJoin("service_card_detail","service_card_detail.id","=","service_card_order.service_card_detail_id")
            ->leftJoin("users","users.id","=","service_card_order.user_id")->where("service_card_order.order_id",Input::get("order_id"))->select("service_card_order.*","service_card_detail.id as card_no","users.phone","users.real_name","users.type")->first();
            if(is_null($sco)){
                $response = Lang::get("scs_error.service_card_order_error_95006");
                break;
            }
            //获取套餐卡信息
            $scb=ServiceCardBase::leftJoin("mkt_user as mk1","mk1.id","=",'service_card_base.created_by')->leftJoin("mkt_user as mk2","mk2.id","=",'service_card_base.updated_by')->select("service_card_base.*","mk1.real_name as create_name","mk2.real_name as update_name")->where("service_card_base.id",$sco->service_card_id)->first();     
            $scbp=$finall_array=array();
            if($scb){//获取服务信息 如果已经存在套餐卡信息                   
                $scbp=ServiceCardBasePack::leftJoin("product_package","product_package.id","=","service_card_base_pack.pack_id")->where("service_card_base_pack.service_card_base_id",$scb->id)->select("service_card_base_pack.*","product_package.name")->get();

                //获取现在 在用的车型参数
                $pc=PricingColumn::all();        
                $temp_pc=array();
                foreach ($pc as $_pc) {
                    $temp_pc[$_pc->id]=$_pc;
                }
                $scbcl=ServiceCardBaseCarlimit::leftJoin("pricing_column_type","pricing_column_type.id","=","service_card_base_carlimit.pric_clo_id")->where("service_card_base_carlimit.service_card_base_id",$scb->id)->select("service_card_base_carlimit.pric_clo_id","service_card_base_carlimit.column_id","pricing_column_type.name")->get();  
                
                foreach ($scbcl as $_scbcl) {
                    if(isset($finall_array[$_scbcl->column_id])){
                        $col=array("id"=>$_scbcl->pric_clo_id,"name"=>$_scbcl->name);
                        $finall_array[$_scbcl->column_id]["item"][]=$col;
                    }else{
                        $temp=$temp_pc[$_scbcl->column_id];
                        $col=array("id"=>$_scbcl->pric_clo_id,"name"=>$_scbcl->name);
                        $finall_array[$_scbcl->column_id]=array("name"=>$temp->name,"id"=>$_scbcl->column_id,"item"=>array($col));
                    }
                }
                
                //查询该门店所销售的套餐卡的适用门店信息
                $shop_info_arr = ServiceCardBaseShopUse::getShopUseInfo([$scb->id]);
                if(isset($shop_info_arr[$scb->id])){
                    $scb->shop_use = array_values($shop_info_arr[$scb->id]);
                } else {
                    $scb->shop_use = [];
                }
            }
            
            //获取支付信息
            $scp=ServiceCardOrderPayRecord::where("order_id",Input::get("order_id"))->where("status",1)->get();
            $shop_amount=array();
            foreach ($scp as $_op) {
                if($_op->pay_type==8){//说明是余额支付// 找出这些余额使用那些支付
                    $arr=DB::select("
                        select sum(aursr.amount)/100 as amount,uad.account_no,ms.`name`,uad.acount_type from acount_user_recharge_spend_record aursr LEFT JOIN acount_user_recharge_record aurr on aurr.id=aursr.aurr_id 
                        LEFT JOIN maintenance_shops ms on ms.id=aurr.shop_id LEFT JOIN user_account_details uad on uad.account_no=aurr.account_no
                        where aursr.type=8 and aursr.buss_id=? GROUP BY uad.acount_type,uad.shop_id",array($_op->id));
                    foreach ($arr as $_arr) {
                        if(isset($shop_amount[$_arr->account_no])){
                            $shop_amount[$_arr->account_no]->amount=$shop_amount[$_arr->account_no]->amount+$_arr->amount;
                        }else{
                            $shop_amount[$_arr->account_no]=$_arr;
                        }
                    }
                }
            }            
            $temp_arr=array("order_info"=>$sco,"service_card_base"=>$scb,"service_card_base_pack"=>$scbp,"car_limit"=>array_values($finall_array),"pay_record"=>$scp,"shop_amount"=>$shop_amount);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "parts_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-07-28 10:31:17
     * @Description: 创建套餐卡销售订单
     */
    public function order_create(){
        $validator = Validator::make(Input::all(),
            array(
                'token'        => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            //检查 本店是否有5个及以上的未完成的套餐卡销售订单
            $sco_count=ServiceCardOrder::where("shop_id",$sc_user->shop_id)->where("status",1411)->count();
            if($sco_count>=5){
                $response = Lang::get("scs_error.service_card_order_error_95007");
                break;
            }
            $sco=new ServiceCardOrder();
            $order_id = Common::createOrderId();
            $sco->order_id = $order_id;
            $sco->status =1411;
            $sco->shop_id =$sc_user->shop_id;
            $sco->create_by = $sc_user->id;
            $sco->save();
            $order_flows = new ServiceCardOrderFlow;
            $order_flows->order_id = $order_id;
            $order_flows->status =1411;
            $order_flows->user_id = $sc_user->id;
            $order_flows->type = 'sc';
            $order_flows->save();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "order_create", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-07-28 11:16:56
     * @Description: 获取当前可售卖的套餐卡信息
     * 过滤条件是 套餐卡可售卖 状态正常 门店包含本门店的套餐卡
     * 
     * @link http://api.anhui.com/v1/scs/service_card/service_card_list?token=53b2544d6c29e928d626657673b88080
     */
    public function service_card_list(){
        $validator = Validator::make(Input::all(),
            array(
                'token'=> 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            //查找可供本门店销售的卡 ID
            $s_id=ServiceCardBaseShop::where("shop_id",$sc_user->shop_id)->where("status",1)->select("service_card_base_id")->get()->toArray();
            $scb=ServiceCardBase::where("sale_status",1)->where(function($query)
            {
                $query->where('sale_limit', 0)
                    ->orWhere(function($query1)
                        {
                            $query1->where('sale_begin_date',"<",Common::currentTimeString())
                                  ->Where('sale_end_date',">",Common::currentTimeString());
                        });
            })
            // ->where(function($query)
            // {
            //     $query->where('date_type', 1)
            //         ->orWhere(function($query1)
            //             {
            //                 $query1->where('begin_date',"<",Common::currentTimeString())
            //                       ->Where('end_date',">",Common::currentTimeString());
            //             });
            // })
            ->whereIn("id",$s_id)->get();
            
            $temp_arr=array("count"=>sizeof($scb),"service_card_info"=>$scb);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);
        }while(false);
        
        Log::info("info", array("system" => "scs" ,"event" => "service_card_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-07-28 13:55:29
     * @Description: 用于展示单个 套餐卡模板的详细信息
     * @link http://api.anhui.com/v1/scs/service_card/service_card_info?token=acd3e73aebb9747057f1e8a772d8f3dc&id=4
     */
    public function service_card_info(){
        $validator = Validator::make(Input::all(),
            array(
                'token'=> 'required',
                'id'=> 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $scb=ServiceCardBase::leftJoin("mkt_user as mk1","mk1.id","=",'service_card_base.created_by')->leftJoin("mkt_user as mk2","mk2.id","=",'service_card_base.updated_by')->select("service_card_base.*","mk1.real_name as create_name","mk2.real_name as update_name")->where("service_card_base.id",Input::get("id"))->first();     
            if(is_null($scb)){
                $response = Lang::get("scs_error.service_card_pack_error_95004");
                break;
            }
            //查询该门店所销售的套餐卡的适用门店信息
            $shop_info_arr = ServiceCardBaseShopUse::getShopUseInfo([$scb->id]);
            if(isset($shop_info_arr[$scb->id])){
                $scb->shop_use = array_values($shop_info_arr[$scb->id]);
            } else {
                $scb->shop_use = [];
            }
                
            //获取服务信息    
            $scbp=ServiceCardBasePack::leftJoin("product_package","product_package.id","=","service_card_base_pack.pack_id")->where("service_card_base_pack.service_card_base_id",$scb->id)->select("service_card_base_pack.*","product_package.name")->get();

            //获取现在 在用的车型参数
            $pc=PricingColumn::all();        
            $temp_pc=array();
            foreach ($pc as $_pc) {
                $temp_pc[$_pc->id]=$_pc;
            }
            $scbcl=ServiceCardBaseCarlimit::leftJoin("pricing_column_type","pricing_column_type.id","=","service_card_base_carlimit.pric_clo_id")->where("service_card_base_carlimit.service_card_base_id",Input::get("id"))->select("service_card_base_carlimit.pric_clo_id","service_card_base_carlimit.column_id","pricing_column_type.name")->get();  
            $finall_array=array();
            foreach ($scbcl as $_scbcl) {
                if(isset($finall_array[$_scbcl->column_id])){
                    $col=array("id"=>$_scbcl->pric_clo_id,"name"=>$_scbcl->name);
                    $finall_array[$_scbcl->column_id]["item"][]=$col;
                }else{
                    $temp=$temp_pc[$_scbcl->column_id];
                    $col=array("id"=>$_scbcl->pric_clo_id,"name"=>$_scbcl->name);
                    $finall_array[$_scbcl->column_id]=array("name"=>$temp->name,"id"=>$_scbcl->column_id,"item"=>array($col));
                }
            }
            $temp_arr=array("service_card_base"=>$scb,"service_card_base_pack"=>$scbp,"car_limit"=>array_values($finall_array));
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);            
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "service_card_info", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

   /**
    * @Author:      lyt
    * @DateTime:  2017-07-28 14:25:36
    * @Description: 选择 
    */
    public function choice_service_card(){
        $validator = Validator::make(Input::all(),
            array(
                'token'        => 'required',
                "order_id"     => 'required',
                "service_card_base_id"     => 'required',  
                "user_id"     => 'required',             
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order_id=Input::get("order_id");
            $service_card_base_id=Input::get("service_card_base_id");
            $user_id=Input::get("user_id");
            $car_no=Input::get("car_no");

            $sco=ServiceCardOrder::find($order_id);
            
            if(is_null($sco)){
                $response = Lang::get("scs_error.service_card_order_error_95006");
                break;
            }
            
            if($sco->user_id!=0&&$sco->user_id==$user_id&&$sco->service_card_id==$service_card_base_id&&$sco->car_no==$car_no){
                $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order_id));
                break;
            }

            if($sco->status!=1411){//判断状态
                $response = Lang::get("scs_error.service_card_order_error_95008");
                break;
            }
            $scopr=ServiceCardOrderPayRecord::where("order_id",$order_id)->whereIn("status",array(1,5,7))->first();
            if($scopr){//如果存在支付成功或者支付中 取消中的 不支持修改
                $response = Lang::get("scs_error.service_card_order_pay_error_95009");
                break;
            }
            $scb=ServiceCardBase::find($service_card_base_id);
            if(is_null($scb)||$scb->sale_status==0){
                $response = Lang::get("scs_error.service_card_status_error_95010");
                break;
            }
            if($scb->sale_limit==1&&(strtotime($scb->sale_begin_date)>time()||strtotime($scb->sale_end_date)<time())){
                $response = Lang::get("scs_error.service_card_time_error_95012");
                break;
            }
            $scbs=ServiceCardBaseShop::where("service_card_base_id",$scb->id)->where("shop_id",$sc_user->shop_id)->where("status",1)->first();//判断是否支持该门店
            if(is_null($scbs)){
                $response = Lang::get("scs_error.service_card_status_error_95011");
                break;
            }
            if($scb->limit_car==1&&empty($car_no)){//如果限制领卡车俩没传车车辆则不能使用
                $response = Lang::get("scs_error.service_card_car_error_95013");
                break;
            }
            $user=Users::find($user_id);

            // if(is_null($user)||$user->type==2||$user->status!=1){//客户不符合要求 
            //     $response = Lang::get("scs_error.service_card_car_error_95014");
            //     break;
            // }
            //取消 企业客户的过滤判断
            if(is_null($user)||$user->status!=1){//客户不符合要求 
                $response = Lang::get("scs_error.service_card_car_error_95014");
                break;
            }

            //判断当前用户是不是已经超过了最大购买限制   0是不限制

            if($scb->buy_number > 0){
                $buy_number = ServiceCardOrder::where("user_id",$user_id)->where('service_card_id',$service_card_base_id)->where('status',1417)
                        ->count();
                if ($scb->buy_number <=  $buy_number){
                    $response = Lang::get("scs_error.service_card_car_error_95021");
                    break;
                }
            }
            
            $sco->amount=$scb->amount;
            $sco->service_card_id=$scb->id;
            $sco->car_no=$car_no;
            $sco->user_id=$user_id;
            $sco->save();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "choice_service_card", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);

    }

    
    /**
     * @Author:      lyt
     * @DateTime:  2017-07-31 09:37:57
     * @Description: 套餐卡的支付信息
     */
    public function order_paydesc(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order_id=Input::get("order_id");

            $order=ServiceCardOrder::find($order_id);
            if(is_null($order)){
                $response = Lang::get("scs_error.service_card_order_error_95006");
                break;
            }
            if($order->status!=1411){//判断状态
                $response = Lang::get("scs_error.service_card_order_error_95008");
                break;
            }
            $user=Users::where("id",$order->user_id)
                ->leftJoin('user_account','user_account.user_id','=','users.id')
                ->select('users.id','users.phone','users.register_source_id','users.real_name','users.sex','users.type','user_account.account_no','user_account.balance','user_account.credit','users.u_dis')
                ->first();
            if(is_null($user)){
                $response = Lang::get("scs_error.service_card_car_error_95015");
                break;
            }
            $cc=DB::select("SELECT  sum(balance) as balance ,sum(credit) as credit,user_id FROM user_account_details WHERE acount_type = 3 and user_id=".$user->id);
            $bb=DB::select("SELECT  sum(balance) as balance ,sum(credit) as credit,user_id FROM user_account_details WHERE acount_type != 3 and user_id=".$user->id);
            $user->balance=$bb[0]->balance;
            $user->credit=$cc[0]->credit+$cc[0]->balance;
            $user->balance_amount=$order->amount;
            $user->payable_amount=$order->pay_amount;
            
            //订单支付记录
            $opr=ServiceCardOrderPayRecord::where('order_id',$order->order_id)->whereIn('status',array(0,1,5,6,7))->select('id','status','pay_type','amount','create_type','create_by','pay_id','tran_no',"sources")->get();
            $opr_amount=ServiceCardOrderPayRecord::where('order_id',$order->order_id)->where('status',5)->sum("amount");
            $user->payin_amount=$opr_amount;
            $temp_arr=array("user_info"=>$user,"order_pay_record"=>$opr);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "order_paydesc", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
    * @Author:      lyt
    * @DateTime:  2017-07-31 10:12:40
    * @Description: 套餐卡的支付
    */
    public function order_pay(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'pay_type' => 'required',
                'amount' => 'required',
                'source' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order_id=Input::get("order_id");

            $order=ServiceCardOrder::find($order_id);
            if(is_null($order)){
                $response = Lang::get("scs_error.service_card_order_error_95006");
                break;
            }
            if($order->status!=1411){//判断状态
                $response = Lang::get("scs_error.service_card_order_error_95008");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }            
            $user=Users::find($order->user_id);
            // if(is_null($user)||$user->type==2||$user->status!=1){//客户不符合要求 
            //     $response = Lang::get("scs_error.service_card_car_error_95014");
            //     break;
            // }
            //取消 企业客户的过滤判断
            if(is_null($user)||$user->status!=1){//客户不符合要求 
                $response = Lang::get("scs_error.service_card_car_error_95014");
                break;
            }
            if(!isset(ServiceCardOrderPayRecord::$pay_pay_type[Input::get("pay_type")])||!in_array(Input::get("source"),ServiceCardOrderPayRecord::$pay_pay_type_source[Input::get("pay_type")])){
                $response = Lang::get("scs_error.service_card_car_error_95016");
                break;
            }
            $response = ServiceCardOrderPayRecord::order_pay($order->order_id,Input::get("pay_type"),Input::get("amount"),$sc_user->id,"sc",Input::get("driver_id"),Input::get("source"));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "order_pay", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    
    /**
     * @Author:      lyt
     * @DateTime:  2017-07-31 13:44:10
     * @Description: 取消套餐卡支付记录
     */
    public function cancel_order_pay(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order_id=Input::get("order_id");

            $order=ServiceCardOrder::find($order_id);
            if(is_null($order)){
                $response = Lang::get("scs_error.service_card_order_error_95006");
                break;
            }
            if($order->status!=1411){//判断状态
                $response = Lang::get("scs_error.service_card_order_error_95008");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }   
            $op=ServiceCardOrderPayRecord::find(Input::get("id"));
            if($op->order_id!=$order->order_id){
                $response = Lang::get("scs_error.order_pay_error_40120");
                break;
            }
            
            if($op->status==5){//说明是支付中
                $response = ServiceCardOrderPayRecord::cancelPayIn($order->order_id,$op->id);
            }else if($op->status==1){
                //时间判断
                if(in_array($op->pay_type, array(2,3))&&$op->sources==2){
                    $response = Lang::get("scs_error.aur_undo_type_error_40126");
                    break;
                }
                if(date("Y-m-d",strtotime($op->implement_time))!=date("Y-m-d",time())){
                    $response = Lang::get("scs_error.order_time_error_40115");
                    break;
                }
                $response = ServiceCardOrderPayRecord::cancel($order->order_id,$op->id,$sc_user->id,"sc");
            }else if($op->status==7){//说明是撤销中
                $response = ServiceCardOrderPayRecord::cancelCanceIn($order->order_id,$op->id,$sc_user->id,"sc");
            }else{
                $response = Lang::get("scs_error.order_pay_error_40120");
                break;
            }            
            // $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "cancel_order_pay", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-07-31 15:10:59
     * @Description: 订单完成  生成用户的相关套餐卡信息
     */
    public function end_order(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order_id=Input::get("order_id");
            $order=ServiceCardOrder::find($order_id);
            if(is_null($order)){
                $response = Lang::get("scs_error.service_card_order_error_95006");
                break;
            }
            if($order->status!=1411){//判断状态
                $response = Lang::get("scs_error.service_card_order_error_95008");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }   
            if(floor($order->amount/100)!=floor($order->pay_amount/100)){
                $response = Lang::get("scs_error.order_pay_record_40114");
                break;
            }
            //如果没有任何成功支付记录不让结算 0元也要添加 0元支付记录
            $op=ServiceCardOrderPayRecord::where("order_id",$order->order_id)->where("status",1)->first();   
            if(is_null($op)){
                $response = Lang::get("scs_error.order_pay_record_40114");
                break;
            }
            $opu=ServiceCardOrderPayUndoRecord::where("order_id",$order->order_id)->where("status",0)->first();   
            if($opu){
                $response = Lang::get("scs_error.order_pay_record_40114");
                break;
            }

            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }        
            //生成套餐卡信息
            $scb=ServiceCardBase::find($order->service_card_id);
            $scbp=ServiceCardBasePack::where("service_card_base_id",$order->service_card_id)->get();
            $time=date("Y-m-d H:i:s",time()+$scb->date_num*24*60*60);

            $card_no = Common::createOrderId();
            $scd=new ServiceCardDetail();
            $scd->id=$card_no;
            $scd->service_card_base_id=$order->service_card_id;
            $scd->status=2;//正常状态
            $scd->user_id=$order->user_id;
            $scd->get_time=Common::currentTimeString();
            $scd->end_date=$scb->date_type==1?$time:$scb->end_date;
            $scd->used_car_no=$order->car_no;
            $scd->shop_id=$order->shop_id;
            $scd->save();
            foreach ($scbp as $_scbp) {
                $scdp=new ServiceCardDetailPack();
                $scdp->service_card_detail_id=$card_no;
                $scdp->service_card_base_id=$order->service_card_id;
                $scdp->amount=$_scbp->amount;
                $scdp->curr_number=$_scbp->number;
                $scdp->number=$_scbp->number;
                $scdp->pack_id=$_scbp->pack_id;
                $scdp->created_by=$sc_user->id;
                $scdp->save();
            }            
            $order_flows = new ServiceCardOrderFlow;
            $order_flows->order_id = $order_id;
            $order_flows->status =1417;
            $order_flows->user_id = $sc_user->id;
            $order_flows->type = 'sc';
            $order_flows->save();

            $order->service_card_detail_id=$card_no;
            $order->pay_time=date("Y-m-d H:i:s",time()+Config::get("config.report_time_diff"));
            $order->status=1417;
            $order->save();         
            Coupons::InvitationCoupon($order->user_id);

            //积分返回
            $temp_amount=ServiceCardOrderPayRecord::where("order_id",$order->order_id)->where("status",1)->whereIn("pay_type",ServiceCardOrderPayRecord::$ei_pay_type)->sum("amount");
            if($temp_amount>0){
                $mc=MemberCoefficient::where("source",3)->where("status",1)->first();
                $ms=MaintenanceShops::find($sc_user->shop_id);

                UserIntegralFlow::record($order->user_id,$sc_user->shop_id,$order->order_id,1,1003,floor($temp_amount*$mc->integral*$ms->integral/100),'套餐卡销售订单完成积分');
                UserExperienceFlow::record($order->user_id,$sc_user->shop_id,$order->order_id,1,1003,floor($temp_amount*$mc->experience*$ms->experience/100),'套餐卡销售订单完成经验');
                Users::checkMember($order->user_id);
            }
            
            //积分返还完毕
            
        
            //推送微信信息     
            //
            //临时发送优惠券的代码
            if(in_array($order->service_card_id,Config::get("activity.service_card_base_id"))){
                $activity = Coupons::getNewUserRegister(Config::get('activity.service_card_activity_id'),$response);
                if(!is_null($activity)){
                    foreach ($activity as  $v) {
                        $coupon_base_info = Coupons::getCouponBaseInfo($v->coupon_base_info_id);
                        if (!$coupon_base_info) {
                            break;
                        }
                        if ($coupon_base_info->status == 0) {
                            break;
                        }
                        if ($coupon_base_info->date_type == 0 && strtotime($coupon_base_info->end_date.' 23:59:59') < strtotime(date('Y-m-d H:i:s', time()))) { //起止时间
                            break;
                        }
                        $coupon_whether_exist = Coupons::getCouponOther($v->coupon_base_info_id);
                        if (!is_null($coupon_whether_exist)) {
                            $coupons = Coupons::find($coupon_whether_exist->id);
                            $coupons->status = 2;
                            $coupons->received_user_id = $order->user_id;
                            $coupons->get_time = date("Y-m-d H:i:s", time());
                            if ($coupon_base_info->date_type == 1) { //顺延日期
                                $coupons->end_date = date("Y-m-d", strtotime("+" . $coupon_base_info->date_num . " day"));
                            }
                            $coupons->save();
                        }
                    }
                }
            }      
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "end_order", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-07-31 16:58:40
     * @Description: 取消订单 
     */
    public function cancel_order(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order_id=Input::get("order_id");
            $order=ServiceCardOrder::find($order_id);
            if(is_null($order)){
                $response = Lang::get("scs_error.service_card_order_error_95006");
                break;
            }
            if($order->status!=1411){//判断状态
                $response = Lang::get("scs_error.service_card_order_error_95008");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            } 
            $scopr=ServiceCardOrderPayRecord::where("order_id",$order_id)->whereIn("status",array(1,5,7))->first();
            if($scopr){//如果存在支付成功或者支付中 取消中的 不支持取消
                $response = Lang::get("scs_error.service_card_order_pay_error_95009");
                break;
            }
            $opu=ServiceCardOrderPayUndoRecord::where("order_id",$order->order_id)->where("status",0)->first();   
            if($opu){
                $response = Lang::get("scs_error.order_pay_record_40114");
                break;
            }

            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }        
            //生成套餐卡信息
                      
            $order_flows = new ServiceCardOrderFlow;
            $order_flows->order_id = $order_id;
            $order_flows->status =1410;
            $order_flows->user_id = $sc_user->id;
            $order_flows->type = 'sc';
            $order_flows->save();
            
            $order->status=1410;
            $order->save();         
            //推送微信信息            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "cancel_order", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
}